package com.worker.ssm.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.worker.ssm.pojo.Employee;
import com.worker.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 查询所有的员工信息
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/employee",method = RequestMethod.GET)
    public String getAllEmployee(Model model){
        /* 查询所有的员工信息 */
        List<Employee> emps = employeeService.getAllEmployee();
        /* 将员工信息在请求域中共享 */
        model.addAttribute("list",emps);
        /* 跳转到employee_list.html */
        return "employee_list";
    }

    /**
     * 查询员工的分页信息
     */
    @RequestMapping(value = "/employee/page/{pageNum}",method = RequestMethod.GET)
    public String getEmployeePage(@PathVariable("pageNum") Integer pageNum,Model model){
        // 获取员工的分页信息
        PageInfo<Employee> page = employeeService.getEmployeePage(pageNum);
        // 将分页数据共享到请求域
        model.addAttribute("page",page);
        return "employee_page";
    }

    /**
     * 插入一个员工信息
     */
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String insertEmployee(Employee employee){
        employeeService.insertEmployee(employee);
        return "redirect:/employee/page/1";
    }

    /**
     * 根据empId删除员工信息
     */
    @RequestMapping(value = "/employee/{empId}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("empId") Integer empId){
        employeeService.deleteEmployee(empId);
        return "redirect:/employee/page/1";
    }

    /**
     * 根据获取到的员工Id来执行更新操作
     * @param empId
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee/{empId}",method = RequestMethod.GET)
    public String getEmployeeById(@PathVariable("empId") Integer empId, Model model){
        Employee employee = employeeService.getEmployeeById(empId);
        model.addAttribute("employee",employee);
        return "employee_update";
    }

    /**
     * 修改员工信息
     */
    @RequestMapping(value = "/employee",method = RequestMethod.PUT)
    public String updateEmployee(Employee emp){
        employeeService.updateEmployee(emp.getEmpId(),emp);
        return "redirect:/employee/page/1";
    }
}
